package org.travel_system.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.travel_system.utils.JwtUtil;
import org.travel_system.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        System.out.println("Token: " + token);
        //验证token
        try {

            Map<String, Object> claims = JwtUtil.parseToken(token);
            System.out.println("Claims: " + claims); // 打印claims
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;

        } catch (Exception e) {
            //http响应状态码为401
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}

